package com.bytedance.douyinclouddemo.utils;


import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;
public class DySignature {
    /**
     * @jdk >= 1.8
     * @param header = {
    "x-nonce-str": "123456",
    "x-timestamp": "456789",
    "x-roomid":    "268",
    "x-msg-type":  "live_gift",
     *                 }
     * @param bodyStr = "abc123你好"
     * @param secret = "123abc"
     * @return PDcKhdlsrKEJif6uMKD2dw==
     */
    public static String signature(Map<String, String> header, String bodyStr, String secret) throws Exception {
        List<String> keyList = new ArrayList<>(4);
        header.forEach((key, val) -> keyList.add(key));
        Collections.sort(keyList, String::compareTo);

        List<String> kvList = new ArrayList<>(4);
        for (String key : keyList) {
            kvList.add(key + "=" + header.get(key));
        }
        String urlParams = String.join("&", kvList);
        String rawData = urlParams + bodyStr + secret;
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(rawData.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(md.digest());
    }
}




